package model

type Collect struct {
	BaseModel
	CollectOpenId string `json:"collect_open_id"`
	ProductId     int    `json:"product_id"`
	Status        int    `json:"status"`
}

func CreateCollectFactory(sqlType string) *Collect {
	return &Collect{BaseModel: BaseModel{DB: UseDbConn(sqlType)}}
}
func (Collect) TableName() string {
	return "tb_collect"
}

// 根据用户id去查询商品的product_id,然后以数组返回
// 根据用户id去查询商品的product_id,然后以数组返回
func (c Collect) GetCollect(id string) []int {
	var productIds []int
	c.DB.Model(&Collect{}).Where("collect_open_id = ?", id).Pluck("product_id", &productIds)
	return productIds
}

func (c Collect) AddCollect(CollectOpenId string, ProductId int) {
	//添加收藏
	//在收藏前检查一下是否已收藏
	if c.DB.Where("collect_open_id = ? and product_id = ?", CollectOpenId, ProductId).First(&Collect{}).RowsAffected > 0 {
		return
	}
	c.DB.Create(&Collect{
		CollectOpenId: CollectOpenId,
		ProductId:     ProductId,
		Status:        1,
	})
}

func (c Collect) CancelCollect(CollectOpenId string, ProductId string) {
	//取消收藏
	c.DB.Where("collect_open_id = ? and product_id = ?", CollectOpenId, ProductId).Delete(&Collect{})
}

// 在 collect_model.go 中添加新结构体（或在 product_model.go 中已有 ProductWithAvatar 的情况下复用）
type ProductWithUser struct {
	Product ProductModel `json:"product"`
	User    UserModel    `json:"user"`
}

func (c Collect) GetMyCollect(CollectOpenId string) ([]ProductWithUser, error) {
	var collects []Collect
	var productIds []int

	// Step 1: 获取收藏的商品 ID 列表
	if err := c.DB.Where("collect_open_id = ?", CollectOpenId).Find(&collects).Error; err != nil {
		return nil, err
	}

	for _, collect := range collects {
		productIds = append(productIds, collect.ProductId)
	}

	var products []ProductModel
	if len(productIds) > 0 {
		// Step 2: 查询商品详情
		err := c.DB.Where("id IN (?)", productIds).Find(&products).Error
		if err != nil {
			return nil, err
		}
	}

	var openIds []string
	for _, product := range products {
		openIds = append(openIds, product.OpenId)
	}

	var users []UserModel
	if len(openIds) > 0 {
		// Step 3: 查询用户信息
		err := c.DB.Where("open_id IN (?)", openIds).Find(&users).Error
		if err != nil {
			return nil, err
		}
	}

	// 构建 userMap 提高查找效率
	userMap := make(map[string]UserModel)
	for _, user := range users {
		userMap[user.OpenId] = user
	}

	// 组合返回结果
	var result []ProductWithUser
	for _, product := range products {
		if user, ok := userMap[product.OpenId]; ok {
			result = append(result, ProductWithUser{
				Product: product,
				User:    user,
			})
		}
	}

	return result, nil
}
